import { setResponseStatus,defineEventHandler,getQuery } from 'h3'

function extToMime(ext: string) {
  ext = ext.toLowerCase()
  if (ext === 'png') return 'image/png'
  if (ext === 'jpg' || ext === 'jpeg') return 'image/jpeg'
  if (ext === 'gif') return 'image/gif'
  if (ext === 'webp') return 'image/webp'
  if (ext === 'svg') return 'image/svg+xml'
  return 'application/octet-stream'
}

export default defineEventHandler(async (event) => {
  const q = getQuery(event)
  const url = q.url ? String(q.url) : ''
  if (!url) {
    setResponseStatus(event, 400)
    return { error: 'missing url' }
  }

  try {
    // Try fetching with common browser headers to improve success rate
    const headers: Record<string,string> = {
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36'
    }
    try {
      const uo = new URL(url)
      headers['Referer'] = uo.origin
    } catch (e) {}

    // limit max size by relying on runtime; try to fetch arrayBuffer
    const arr = await $fetch(url, { method: 'GET', responseType: 'arrayBuffer', headers })
    const buf = Buffer.from(arr as ArrayBuffer)

    // determine mime from extension if possible
    let mime = 'application/octet-stream'
    try {
      const u = new URL(url)
      const path = u.pathname
      const ext = path.split('.').pop() || ''
      mime = extToMime(ext)
    } catch (e) {}

    const res = event.node.res
    res.setHeader('Content-Type', mime)
    res.setHeader('Cache-Control', 'public, max-age=3600')
    // same-origin endpoint, but allow CORS for flexibility
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.end(buf)
    return ''
  } catch (err: any) {
    setResponseStatus(event, 502)
    return { error: String(err && err.message ? err.message : err) }
  }
})
